import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

import type { CartItem } from '@/types'

export const useCartStore = defineStore('cart', () => {
  // state
  const items = ref<CartItem[]>([])
  const selectedItems = ref<CartItem[]>([])

  // getters
  const total = computed(() => items.value.reduce((sum, item) => sum + item.price * item.quantity, 0))
  const selectedTotal = computed(() => selectedItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0))
  const totalQuantity = computed(() => items.value.reduce((sum, item) => sum + item.quantity, 0))
  const isEmpty = computed(() => items.value.length === 0)

  const getItemById = (id: string) => items.value.find(item => item.id === id)
  const isInCart = (productId: string) => items.value.some(item => item.id === productId)

  // actions
  function addItem(item: CartItem) {
    const existingItem = getItemById(item.id)
    if (existingItem) {
      existingItem.quantity += item.quantity
    } else {
      items.value.push(item)
    }
  }

  function removeItem(id: string) {
    const index = items.value.findIndex(item => item.id === id)
    if (index !== -1) {
      items.value.splice(index, 1)
    }
  }

  function clearCart() {
    items.value = []
    selectedItems.value = []
  }

  return {
    items,
    selectedItems,
    total,
    selectedTotal,
    totalQuantity,
    isEmpty,
    getItemById,
    isInCart,
    addItem,
    removeItem,
    clearCart
  }
}, {
  persist: true // 现在这个选项会被正确识别
})